<?php
class Cache
{
	private $tmp_dir;
	public $lifetime=3600;
	public $id;
	public $group;
	
	
	public function __construct($lifetime=3600,$group="")
	{
		$this->lifetime=$lifetime;
		$this->group=$group;
		$front=Registry::getInstance();
		$front=$front->get("frontcontroller");
		$this->tmp_dir=$front->getRootDir()."application/tmp/";
		if(!empty($group))
		{
			if(!file_exists($this->tmp_dir.$group."/")||!is_dir($this->tmp_dir.$group."/"))
			{
				mkdir($this->tmp_dir.$group."/",777);
			}
			$this->tmp_dir.=$group."/";
		}
	}
	
	
	public function get($id)
	{
		$file=$this->tmp_dir.$id.".txt";
		if(file_exists($file))
		{
			if(time()-filemtime($file)<$this->lifetime)
			{
				$file=file_get_contents($file);
				return unserialize($file);
			}
			else 
			{
				unlink($file);
			}
		}
		return null;
	}
	
	public function save($data,$id)
	{
		$data=serialize($data);
		$file=$this->tmp_dir.$id.".txt";
		file_put_contents($file,$data);
	}
	
	public function startCache($id)
	{
		$this->id=$id;
		ob_start();
	}
	
	public function saveCache()
	{
		$data=ob_get_contents();
		$this->save($data,$this->id);
		ob_end_flush();
	}
}